<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="听证告知书文号" prop="hearingNoticeNo">
            <el-input v-model="formData.hearingNoticeNo" :disabled="disabled" placeholder="请输入听证告知书文号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法定代表人" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="营业执照类型" prop="businessType">
            <el-input v-model="formData.businessType" disabled placeholder="请输入营业执照类型" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="formData.unifiedSocialCreditCode" disabled placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
            <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="听证申请时间" :rules="rules.requestTime" prop="requestTime">
            <el-date-picker
              v-model="formData.requestTime"
              type="date"
              placeholder="请选择时间"
              disabled
              :value-format="'YYYY-MM-DD'" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="案由" prop="caseCause">
            <el-input v-model="formData.caseCause" disabled placeholder="请输入案由" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="听证时间" :rules="rules.hearingTime" prop="hearingTime">
            <el-date-picker
              v-model="formData.hearingTime"
              type="datetime"
              placeholder="请选择时间"
              :disabled="disabled"
              :value-format="'YYYY-MM-DD HH:mm:ss'" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="听证地址" prop="hearingAddress">
            <el-input v-model="formData.hearingAddress" :disabled="disabled" placeholder="请输入听证地址" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否公开" prop="isPublic">
            <el-radio-group v-model="formData.isPublic" :disabled="disabled">
              <el-radio v-for="item in isOpenList" :key="item.value" :value="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="主持人" prop="hostName">
            <el-input v-model="formData.hostName" :disabled="disabled" placeholder="请输入主持人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="主持人单位" prop="hostUnit">
            <el-input v-model="formData.hostUnit" :disabled="disabled" placeholder="请输入主持人单位" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="主持人职务" prop="hostPosition">
            <el-input v-model="formData.hostPosition" :disabled="disabled" placeholder="请输入主持人职务" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录人" prop="recorderName">
            <el-input v-model="formData.recorderName" :disabled="disabled" placeholder="请输入记录人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录单位" prop="recorderUnit">
            <el-input v-model="formData.recorderUnit" :disabled="disabled" placeholder="请输入记录单位" />
          </el-form-item>
          ··
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录职务" prop="recorderPosition">
            <el-input v-model="formData.recorderPosition" :disabled="disabled" placeholder="请输入记录职务" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="申请听证员、主持人回避最晚时间"
            :rules="rules.latestAttendanceTime"
            prop="latestAttendanceTime"
            class="long-label">
            <el-date-picker
              v-model="formData.latestAttendanceTime"
              type="date"
              placeholder="请选择时间"
              :disabled="disabled"
              :value-format="'YYYY-MM-DD'" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="申请延期最晚时间"
            :rules="rules.latestPostponementTime"
            prop="latestPostponementTime"
            class="lone-label">
            <el-date-picker
              v-model="formData.latestPostponementTime"
              type="date"
              placeholder="请选择时间"
              :disabled="disabled"
              :value-format="'YYYY-MM-DD'" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="contactPerson">
            <el-select
              v-model="formData.contactPerson"
              filterable
              clearable
              :disabled="disabled"
              placeholder="请选择联系人"
              @change="handlepartyChange">
              <el-option v-for="item in inspectorOptions" :key="item.value" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" :disabled="disabled" placeholder="请输入联系人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人地址" prop="contactAddress">
            <el-input v-model="formData.contactAddress" :disabled="disabled" placeholder="请输入联系人地址" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人邮编" prop="contactPostalCode">
            <el-input v-model="formData.contactPostalCode" :disabled="disabled" placeholder="请输入联系人邮编" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人邮箱" prop="contactEmail">
            <el-input v-model="formData.contactEmail" :disabled="disabled" placeholder="请输入联系人邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch } from 'vue'
import {
  getNotification,
  addNotification,
  updateNotification,
  getCaseList,
  getContent,
  previewPdf,
} from '@/api/hearingNotice/notification.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import { getUserEnforcementNo, getUserInfo } from '@/api/system/user.js'
import { commonRules } from '@/components/DynamicForm/config'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: undefined,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

// Emits
const emit = defineEmits(['handleSubmit'])
const isOpenList = [
  { value: '2', label: '公开' },
  { value: '1', label: '不公开' },
]
// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  hearingNoticeNo: null,
  partyName: null,
  streetOfCompanyAddress: null,
  address: null,
  legalRepresentative: null,
  businessType: null,
  requestTime: null,
  caseCause: null,
  hearingTime: null,
  hearingAddress: null,
  isPublic: null,
  hostName: null,
  hostUnit: null,
  hostPosition: null,
  recorderName: null,
  recorderUnit: null,
  recorderPosition: null,
  latestAttendanceTime: null,
  latestPostponementTime: null,
  contactPerson: null,
  contactPhone: null,
  contactAddress: null,
  contactPostalCode: null,
  contactEmail: null,
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地点'))
  } else {
    callback()
  }
}
// Form validation rules
const rules = {
  caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  hearingNoticeNo: [{ required: true, message: '听证告知书文号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  businessType: [{ required: true, message: '营业执照类型不能为空', trigger: ['blur', 'change'] }],
  unifiedSocialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  requestTime: [{ required: true, message: '听证申请时间不能为空', trigger: 'change' }],
  caseCause: [{ required: true, message: '案由不能为空', trigger: ['blur', 'change'] }],
  hearingTime: [{ required: true, message: '听证时间不能为空', trigger: 'change' }],
  hearingAddress: [{ required: true, message: '听证地址不能为空', trigger: ['blur', 'change'] }],
  isPublic: [{ required: true, message: '是否公开不能为空', trigger: 'change' }],
  hostName: [{ required: true, message: '主持人不能为空', trigger: ['blur', 'change'] }],
  hostUnit: [{ required: true, message: '主持人单位不能为空', trigger: ['blur', 'change'] }],
  hostPosition: [{ required: true, message: '主持人职务不能为空', trigger: ['blur', 'change'] }],
  recorderName: [{ required: true, message: '记录人不能为空', trigger: ['blur', 'change'] }],
  recorderUnit: [{ required: true, message: '记录单位不能为空', trigger: ['blur', 'change'] }],
  recorderPosition: [{ required: true, message: '记录职务不能为空', trigger: ['blur', 'change'] }],
  latestAttendanceTime: [{ required: true, message: '最新出席时间不能为空', trigger: 'change' }],
  latestPostponementTime: [{ required: true, message: '最新延期时间不能为空', trigger: 'change' }],
  contactPerson: [{ required: true, message: '联系人不能为空', trigger: ['blur', 'change'] }],
  contactPhone: [commonRules.phone],
  contactAddress: [{ required: true, message: '联系人地址不能为空', trigger: ['blur', 'change'] }],
  contactPostalCode: [commonRules.postCode],
  contactEmail: [commonRules.email],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    hearingNoticeNo: null,
    partyName: null,
    streetOfCompanyAddress: null,
    address: null,
    legalRepresentative: null,
    businessType: null,
    requestTime: null,
    caseCause: null,
    hearingTime: null,
    hearingAddress: null,
    isPublic: null,
    hostName: null,
    hostUnit: null,
    hostPosition: null,
    recorderName: null,
    recorderUnit: null,
    recorderPosition: null,
    latestAttendanceTime: null,
    latestPostponementTime: null,
    contactPerson: null,
    contactPhone: null,
    contactAddress: null,
    contactPostalCode: null,
    contactEmail: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
}

const inspectorOptions = ref([])

const getUserList = async () => {
  const res = await getUserEnforcementNo({})
  if (res.data.length > 0) {
    inspectorOptions.value = res.data.map(item => {
      return { value: item.name, label: item.name, enforcementNo: item.enforcementNo, userId: item.userId }
    })
  }
}

getUserList()
// 选择联系人
const handlepartyChange = async val => {
  const inspector = inspectorOptions.value.find(item => item.value === val)
  if (!inspector) {
    formData.value.contactPhone = ''
    formData.value.contactEmail = ''
    return
  }
  const res = await getUserInfo(inspector.userId)
  formData.value.contactPhone = res.data?.phonenumber || ''
  formData.value.contactEmail = res.data?.email || ''
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getNotification(id)
      formData.value = res.data
      formData.value.addressObj = {
        photoLocation: res.data.address,
        streetOfPhotoLocation: res.data.streetOfCompanyAddress,
      }
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.hearingNoticeNo = ''
      formData.value.partyName = ''
      formData.value.partyId = ''
      formData.value.legalRepresentative = ''
      formData.value.businessType = ''
      formData.value.unifiedSocialCreditCode = ''
      formData.value.caseCause = ''
      formData.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      formData.value.requestTime = ''
      formData.value.hearingAddress = ''
      formData.value.hearingRequestId = ''
      return
    }
    const res = await registrationcaseDetail(val)
    const {
      partyName,
      partyId,
      legalRepresentative,
      businessType,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
      caseCause,
    } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.partyName = partyName
    formData.value.partyId = partyId
    formData.value.legalRepresentative = legalRepresentative
    formData.value.businessType = businessType
    formData.value.unifiedSocialCreditCode = unifiedSocialCreditCode
    formData.value.caseCause = caseCause
    formData.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    const res2 = await getContent(val)
    formData.value.requestTime = res2.data.requestTime
    formData.value.hearingAddress = res2.data.hearingAddress
    formData.value.hearingRequestId = res2.data.hearingRequestId
    resolve()
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const submitForm = (isPreview = false) => {
  return new Promise((resolve, reject) => {
    console.log('提交数据', formData.value)
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        if (isPreview === true) {
          resolve(formData.value)
          return
        }
        formData.value.address = formData.value.addressObj.photoLocation
        formData.value.streetOfCompanyAddress = formData.value.addressObj.streetOfPhotoLocation
        let result
        if (formData.value.id) {
          result = await updateNotification(formData.value)
        } else {
          result = await addNotification(formData.value)
        }

        ElMessage.success('提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(error => {
        reject(error)
      })
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
